package com.vegetable.modules.service.finance;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.vegetable.modules.entity.baseData.FundAccount;
import com.vegetable.modules.service.baseData.IFundAccountService;
import com.vegetable.modules.service.wx.WxCpMessageService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.bean.article.NewArticle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 资金账户余额定时任务
 * 每天晚上9点统计账户余额并发送图文消息到企业微信
 *
 * @author Qoder
 */
@Slf4j
@Component
public class FundAccountBalanceScheduledTask {

    @Autowired
    private IFundAccountService fundAccountService;

    @Autowired
    private WxCpMessageService wxCpMessageService;

    // 企业微信管理员用户ID，多个用户用|分隔
    @Value("${wechat.cp.admin.userIds:DingYuXin}")
    private String adminUserIds;

    /**
     * 每天晚上9点执行资金账户余额统计并推送图文消息到企业微信
     */
    @Scheduled(cron = "0 0 21 * * ?")
    public void pushFundAccountBalanceReport() {
        try {
            log.info("开始执行资金账户余额统计任务");
            
            // 获取所有未删除的资金账户
            List<FundAccount> fundAccounts = fundAccountService.list(new QueryWrapper<FundAccount>()
                    .eq("is_del", 0));
            
            if (fundAccounts != null && !fundAccounts.isEmpty()) {
                // 创建图文消息
                List<NewArticle> articles = createFundAccountBalanceArticles(fundAccounts);
                
                // 推送数据到企业微信管理员
                String[] userIds = adminUserIds.split("\\|");
                
                for (String userId : userIds) {
                    try {
                        boolean result = wxCpMessageService.sendNewsMessageToUser(userId.trim(), articles);
                        if (result) {
                            log.info("资金账户余额报告已推送到企业微信用户: {}", userId);
                        } else {
                            log.error("推送资金账户余额报告到企业微信用户失败: {}", userId);
                        }
                    } catch (WxErrorException e) {
                        log.error("推送资金账户余额报告到企业微信用户失败: {}", userId, e);
                    }
                }
            } else {
                log.warn("未找到有效的资金账户数据");
            }
        } catch (Exception e) {
            log.error("执行资金账户余额统计任务时发生异常", e);
        }
    }

    /**
     * 创建资金账户余额图文消息
     *
     * @param fundAccounts 资金账户列表
     * @return 图文消息列表
     */
    private List<NewArticle> createFundAccountBalanceArticles(List<FundAccount> fundAccounts) {
        List<NewArticle> articles = new ArrayList<>();
        
        // 汇总信息
        NewArticle summaryArticle = new NewArticle();
        summaryArticle.setTitle("资金账户余额日报");
        summaryArticle.setDescription("统计时间: " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + "\n账户总数: " + fundAccounts.size() + "个");
        summaryArticle.setUrl("https://example.com/financial-analysis.html");
        // 使用有效的图片URL，避免null值
        summaryArticle.setPicUrl("https://www.baidu.com/img/flexible/logo/pc/result.png");
        articles.add(summaryArticle);
        
        // 总余额统计
        BigDecimal totalBalance = fundAccounts.stream()
                .map(FundAccount::getTotalBalance)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        
        NewArticle totalArticle = new NewArticle();
        totalArticle.setTitle("账户总余额");
        totalArticle.setDescription("所有账户总余额: " + (totalBalance != null ? totalBalance.setScale(2, BigDecimal.ROUND_HALF_UP).toString() : "0.00") + "元");
        totalArticle.setUrl("https://example.com/financial-analysis.html");
        totalArticle.setPicUrl("https://www.baidu.com/img/flexible/logo/pc/result.png");
        articles.add(totalArticle);
        
        // 各账户详细信息（最多显示6个账户，确保总文章数不超过8条）
        // 企业微信限制：图文消息的文章数量不能超过8条
        int displayCount = Math.min(fundAccounts.size(), 6);
        for (int i = 0; i < displayCount; i++) {
            FundAccount account = fundAccounts.get(i);
            NewArticle accountArticle = new NewArticle();
            accountArticle.setTitle(getAccountTypeName(account.getAccountType()) + " - " + account.getAccountName());
            // 限制描述长度，避免超出企业微信限制
            String description = "账户名称: " + account.getAccountName() + "\n" +
                               "账户类型: " + getAccountTypeName(account.getAccountType()) + "\n" +
                               "关联卡号: " + (account.getCardNo() != null && !account.getCardNo().isEmpty() ? account.getCardNo() : "无") + "\n" +
                               "当前余额: " + (account.getTotalBalance() != null ? account.getTotalBalance().setScale(2, BigDecimal.ROUND_HALF_UP).toString() : "0.00") + "元";
            
            // 企业微信限制描述长度为512字符
            if (description.length() > 512) {
                description = description.substring(0, 509) + "...";
            }
            accountArticle.setDescription(description);
            accountArticle.setUrl("https://example.com/financial-analysis.html");
            accountArticle.setPicUrl("https://www.baidu.com/img/flexible/logo/pc/result.png");
            articles.add(accountArticle);
        }
        
        return articles;
    }

    /**
     * 获取账户类型名称
     *
     * @param accountType 账户类型代码
     * @return 账户类型名称
     */
    private String getAccountTypeName(Integer accountType) {
        if (accountType == null) return "未知类型";
        
        switch (accountType) {
            case 0: return "现金";
            case 1: return "微信";
            case 2: return "支付宝";
            case 3: return "中国银行卡";
            case 4: return "建设银行";
            case 5: return "农业银行";
            case 6: return "工商银行";
            case 7: return "潍坊银行";
            case 8: return "农村信用社";
            case 9: return "邮政储蓄";
            default: return "其他银行";
        }
    }
    
    /**
     * 用于测试的临时方法，每分钟执行一次（仅用于测试）
     */
    // @Scheduled(cron = "0 * * * * ?")
    public void testPushFundAccountBalanceReport() {
        log.info("测试执行资金账户余额统计任务");
        pushFundAccountBalanceReport();
    }
}